package com.miaosha.controller;

import com.github.pagehelper.PageInfo;
import com.miaosha.entity.Goods;
import com.miaosha.entity.MiaoShaGoods;
import com.miaosha.entity.dto.AuditReqDto;
import com.miaosha.entity.vo.ListProductVo;
import com.miaosha.service.GoodsService;
import com.miaosha.service.MiaoShaGoodsService;
import com.miaosha.utils.AjaxResult;
import com.miaosha.utils.CommonResult;
import com.miaosha.utils.JwtTokenUtil;
import com.miaosha.utils.TableDataInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/product")
public class ProductController {

    @Resource
    private GoodsService goodsService;

    @Resource
    private MiaoShaGoodsService miaoShaGoodsService;

    @Autowired
    HttpServletRequest request;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @PostMapping("/list")
    public CommonResult list(@RequestBody ListProductVo productVo) {
        System.out.println("pvo:" + productVo);
        String token = request.getHeader("Authorization").substring(7);
        Long userId = jwtTokenUtil.getUserIdFromToken(token);
        List<Goods> list = goodsService.listByName(productVo.getProductName(), userId);
        return CommonResult.success(list);
    }

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return AjaxResult.success(goodsService.getById(id));
    }

    @PostMapping
    public CommonResult add(@Validated @RequestBody Goods goods) {
        String token = request.getHeader("Authorization").substring(7);
        Long userId = jwtTokenUtil.getUserIdFromToken(token);
        goods.setUserId(userId);
        goodsService.save(goods);
        return CommonResult.success(null);
    }


    @PutMapping
    public CommonResult edit(@Validated @RequestBody Goods goods) {
        goodsService.updateById(goods);
        return CommonResult.success(null);
    }

    @DeleteMapping("/{id}")
    public CommonResult remove(@PathVariable Long id) throws Exception {
        goodsService.removeGood(id);
        return CommonResult.success(null);
    }

    //下架
    @PostMapping("/remove/{ids}")
    public AjaxResult removeProduct(@PathVariable Long[] ids) {
        for (Long id : ids) {
            MiaoShaGoods miaoShaGoods = miaoShaGoodsService.getById(id);
            if (null == miaoShaGoods) {
                return AjaxResult.error("该商品已下架，操作失败");
            }
        }
        boolean b = miaoShaGoodsService.removeBatchByIds(Arrays.asList(ids));
        // 下架商品, redis商品需要删除
        miaoShaGoodsService.removeRedis(ids);
        return b ? AjaxResult.success() : AjaxResult.error();
    }

    //上架
    @PostMapping("/shelves")
    @Transactional
    public AjaxResult shelves(@RequestBody MiaoShaGoods miaoShaGoods) {
        if (null == miaoShaGoods) {
            return AjaxResult.error("请选择商品");
        }
        if (null == miaoShaGoods.getGoodsId() || null == miaoShaGoods.getStock() || null == miaoShaGoods.getStartTime() || null == miaoShaGoods.getEndTime() || null == miaoShaGoods.getPrice()) {
            return AjaxResult.error("请检查参数");
        }
        Goods goods = goodsService.getById(miaoShaGoods.getGoodsId());
        if (goods.getStock() < miaoShaGoods.getStock()) {
            return AjaxResult.error("该商品库存不足");
        }
        boolean save = miaoShaGoodsService.save(miaoShaGoods);

        // 将秒杀商品信息保存到redis中
        miaoShaGoodsService.add2Redis(miaoShaGoods);
        return save ? AjaxResult.success() : AjaxResult.error();
    }

    @PostMapping("/audit")
    public CommonResult audit(@RequestBody AuditReqDto auditReqDto) {
        goodsService.audit(auditReqDto);
        return CommonResult.success(null);
    }

    @GetMapping("/awaitAudit")
    public CommonResult awaitAudit() {
        List<Goods> goods = goodsService.list();
        Collections.sort(goods, new Comparator<Goods>() {
            @Override
            public int compare(Goods goods1, Goods goods2) {
                return goods1.getAuditStatus() - goods2.getAuditStatus();
            }
        });
        return CommonResult.success(goods);
    }

    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }
}
